<template>
  <div class="monitor-box" v-loading="loading">
    <div v-show="departmentShow" class="monitor-silder" :style="monitorSilderStyle">
      <department-tree :value="query.deptId" default-expand @selected="handleSelect" @loaded="departmentLoaded" />
    </div>
    <div class="monitor-main" :style="monitorMainStyle">
      <div class="department-title">
        <el-row>
          <el-col :span="4">
            <el-button type="text" :icon="departmentCollapse?'el-icon-s-fold':'el-icon-s-unfold'"
              @click="toggleDepartment"></el-button>
          </el-col>
          <el-col :span="16" class="department-name">
            <span>{{ selectDept.label }}</span>
          </el-col>
        </el-row>
        <environment-controller v-if="haveEnvironment" :value="environmentDevice" />
      </div>
      <div class="device-content">
        <div class="first-box">
          <el-card class="device-card module-card">
            <module-chart :devices="list" />
          </el-card>
        </div>
        <div class="device-group">
          <el-card v-for="(each,index) in validList" :key="'device_'+index" class="device-card"
            :style="controllerCardStyle(each)">
            <div slot="header">
              <span v-if="supportGroupByType(each.type)">
                <dict-tag :options="dict.type.haij_device_type" :value="each.type" />
              </span>
              <span v-else-if="nameByDevice(each)">{{ nameByDevice(each) }}</span>
              <span v-else>
                <dict-tag :options="dict.type.haij_device_type" :value="each.type" />
              </span>
            </div>
            <div :is="controllerByType(each.type)" :value="each">
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import deviceAPI from '@/api/device/device'
  import DepartmentTree from '@/views/system/components/DepartmentTree.vue'
  import Controllers from '@/views/device/components/controller/index'
  import {
    DEVICE_CONTROLLER_WIDTH
  } from "@/utils";
  import {
    controllerByType,
    controllerWidthByType,
    controllerHeightByType,
    supportGroupByType,
    nameByDevice
  } from '@/views/device/common'
  import ModuleChart from '@/views/device/device/ModuleChart.vue'
  import {
    mapMutations
  } from 'vuex'

  export default {
    name: 'DepartmentDevice',
    dicts: ["haij_device_type"],
    components: {
      DepartmentTree,
      ModuleChart,
      ...Controllers,
    },
    data() {
      return {
        query: {
          deptId: null
        },
        selectDept: {},
        loading: false,
        list: [],
        validList: [],
        environmentDevice: {},
        departmentCollapse: true,
        departmentShow: true
      }
    },
    computed: {
      haveEnvironment() {
        return this.environmentDevice && this.environmentDevice.code !== undefined
      },
      monitorSilderStyle() {
        const {
          departmentCollapse
        } = this
        return {
          width: departmentCollapse ? '260px' : '0px',
          opacity: departmentCollapse ? 1 : 0
        };
      },
      monitorMainStyle() {
        const {
          departmentCollapse
        } = this
        return {
          width: departmentCollapse ? 'calc(100% - 260px)' : '100%'
        }
      },
    },
    created() {
      const deptId = localStorage.getItem('device_monitor_dept_id')
      if (deptId) {
        this.query.deptId = parseInt(deptId)
      }
      this.queryData()
    },
    mounted() {

    },
    destroyed() {
      this.setFreezeSidebar(false)
    },
    methods: {
      ...mapMutations('app', ['setFreezeSidebar']),
      nameByDevice,
      controllerByType,
      supportGroupByType,
      controllerWidthByType,
      controllerHeightByType,
      controllerCardStyle(each) {
        var width = ''
        var height = null
        if (each.type === 15 || each.type == 17) {
          width = 'calc(100% - 20px)'
        } else {
          width = controllerWidthByType(each.type) + 'px'
          height = (controllerHeightByType(each.type) + 50) + 'px'
        }
        return {
          width: width,
          height
        }
      },
      toggleDepartment() {
        this.departmentCollapse = !this.departmentCollapse
      },
      queryData() {
        if (!this.query.deptId) {
          return
        }
        const vm = this
        deviceAPI.list(this.query).then(res => {
          vm.setList(res.data)
        })
      },
      setList(list) {
        // this.environmentDevice = null
        const bleDeviceMap = {}
        const visibleList = []
        for (var j = 0; j < list.length; j++) {
          const each = list[j]
          const type = controllerByType(each.type)
          if (type === 'DeviceController' || type ==
            'IChargingController') {
            continue
          }
          if (type == 'ControlController') {
            const code = each.code.split('@')[0]
            bleDeviceMap[code] = Object.assign({}, bleDeviceMap[code], {
              control: each
            })
            continue
          }
          if (type == 'BleGatewayController') {
            continue
            // gatewayMap[code] = Object.assign({}, gatewayMap[code], {
            //   gateway: each
            // })
          }
          visibleList.push(each)
        }
        const validList = []
        const typeMap = {}
        for (var i = 0; i < visibleList.length; i++) {
          const each = visibleList[i]
          const type = controllerByType(each.type)
          if (type === 'PlatformController' && each.code.indexOf('BleGate_') === 0) {
            const gatewayCode = each.code.split('@')[0]
            each.control = bleDeviceMap[gatewayCode] && bleDeviceMap[gatewayCode].control ? bleDeviceMap[gatewayCode]
              .control : null
          }
          if (!supportGroupByType(each.type)) {
            validList.push(each)
            continue
          }
          if (typeMap[type] == undefined) {
            typeMap[type] = Object.assign({
              array: [each]
            }, each)
          } else {
            typeMap[type].array.push(each)
          }
        }
        this.environmentDevice = Object.assign({}, typeMap['EnvironmentController'])
        delete typeMap.EnvironmentController
        for (var k in typeMap) {
          const value = typeMap[k]
          validList.push(value)
        }
        this.list = [].concat(list)
        this.validList = validList.sort(function (a, b) {
          return (a.type !== 14 && b.type !== 14) ? a.type - b.type : b.type === 14 ? 1 : -1
        })
      },
      handleSelect(department) {
        this.selectDept = Object.assign({}, department)
        localStorage.setItem('device_monitor_dept_id', department.id)
        this.query.deptId = department.id
        this.queryData()
      },
      departmentLoaded(list) {
        if (list === undefined || list === null || list.length !== 1) {
          return
        }
        const {
          children
        } = list[0]
        if (children === undefined || children === null || children.length === 0) {
          this.handleSelect(list[0])
          this.departmentCollapse = false
          return
        }
        this.departmentLoaded(children)
      }
    }
  }

</script>
<style scoped>
  .monitor-box {
    display: flex;
    flex-direction: row;
    padding: 15px;
  }

  .monitor-silder {
    margin-left: 5px;
    width: 260px;
    transition: width 0.23s;
  }

  .monitor-main {
    width: calc(100% - 260px);
    margin-left: 5px;
    /* margin: 5px; */
  }

  .department-title {
    width: 100%;
  }

  .department-name {
    font-weight: 800;
    font-size: 20;
    text-align: center;
  }

  .device-content {
    /* display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    height: calc(100vh - 160px); */
    /* height: 800px; */
  }

  .first-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }

  .device-group {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }

  .device-card {
    margin-top: 10px;
    margin-right: 10px;
    flex-grow: 1;
  }

  .module-card {
    min-width: 360px;
  }

</style>
